package com.wonders.myservlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "param-servlet",
        value = {"/params", "/helloparam"},
        initParams = {
                @WebInitParam(name = "age", value = "20"),
                @WebInitParam(name = "sex", value = "1"),
        },
        loadOnStartup = 2 // tomcat启动时就初始化这个servlet
)
public class ParamServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("ParamServlet初始化了");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.append("Hello Servlet3.0,I'm late!<br/>");

        // 获取servlet名称
        writer.append("servletName = " + this.getServletName() + "<br/>");

        // 获取初始化参数
        writer.append("initParams sex = " + this.getInitParameter("sex") + "<br/>");
    }
}
